Popular Searches
Popular Course Categories
Popular Courses

Introduction to Components

Introduction to Components

React Components

Introduction to Components in React JS – Detailed Notes

Topic: Introduction to Components

Technology: React JS

Level: Beginner to Intermediate

Learning Objective: Understand React components, how to create and use them, how components communicate through props, and how to build reusable user interfaces.

React JS Training Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Are Components in React?

Components are the fundamental building blocks of a React application. A component is a reusable, independent piece of the user interface (UI) that describes how a particular part of the application should appear and behave.

A component can represent a small element, such as a button or a search bar, or a large section, such as a navigation menu, dashboard, product page, or complete webpage.

React allows developers to combine multiple components to build complex user interfaces in a structured and maintainable way.

Example

function Welcome() {
  return <h1>Welcome to React JS!</h1>;
}

export default Welcome;

In this example:

  • function Welcome() defines a React function component.
  • return specifies the JSX that describes the UI.
  • displays a heading.

  • export default Welcome makes the component available for importing into another file.

2. Why Are Components Important?

Components help developers organize an application into smaller, manageable parts rather than writing the entire interface in one large file.

Main advantages

  • Reusability: The same component can be used multiple times.
  • Maintainability: Individual components can be updated without rewriting the entire application.
  • Readability: Smaller components make code easier to understand.
  • Separation of concerns: Different components can handle different parts of the UI.
  • Testing: Individual components can be tested separately.
  • Scalability: Large applications can be organized into manageable components.
  • Team collaboration: Developers can work on separate components or features.

Example: Without components and with components

Without reusable components: A developer may repeat the same product-card markup many times, making updates difficult.

With reusable components: A single ProductCard component can display different products by receiving different props.


3. Real-World Examples of React Components

Most modern websites and applications can be divided into components.

Component Purpose Example
Header Displays the top section of a page Website logo and title
Navbar Provides navigation links Home, About, Services
SearchBar Allows users to search content Product search field
Button Performs a user action Submit or Login
ProductCard Displays product information Image, name, price
Sidebar Displays secondary navigation Dashboard menu
Footer Displays bottom-page information Copyright and contact links
LoginForm Collects authentication details Email and password fields

4. Types of Components in React

React supports function components and class components. In modern React development, function components are generally recommended, especially when using Hooks such as useState and useEffect.

4.1 Function Components

A function component is a JavaScript function that returns React elements, commonly written using JSX.

Example

function Greeting() {
  return (
    <div>
      <h2>Hello, Student!</h2>
      <p>Welcome to React JS.</p>
    </div>
  );
}

export default Greeting;

Features:

  • Defined using JavaScript functions.
  • Can receive props as arguments.
  • Can use Hooks to manage state and other React features.
  • Are the standard choice for most new React components.

4.2 Class Components

A class component is defined using an ES6 JavaScript class that extends React's Component class. It includes a render() method that returns the UI.

Example

import { Component } from "react";

class Greeting extends Component {
  render() {
    return (
      <div>
        <h2>Hello, Student!</h2>
        <p>Welcome to React JS.</p>
      </div>
    );
  }
}

export default Greeting;

Features:

  • Defined using JavaScript classes.
  • Use the render() method to describe the UI.
  • Can receive props and manage state using class-specific APIs.
  • Remain supported in React, but function components are recommended for new code.

Function Components vs. Class Components

Feature Function Component Class Component
Definition JavaScript function JavaScript class
UI output Returns JSX or other React nodes Usually returns JSX from render()
Props Received as function parameters Accessed using this.props
State Can use Hooks such as useState Usually managed using this.state and this.setState()
Hooks Can use Hooks at the top level of components Cannot use Hooks inside class components
Syntax Generally simpler and more concise Requires class-based syntax
Recommendation Preferred for most new components Useful when maintaining existing class-based code

5. How to Create a React Component

Creating a function component usually involves defining a JavaScript function, returning JSX, and exporting the component when it needs to be used in another file.

Step 1: Define the component

function Header() {
  return <h1>My Website</h1>;
}

Step 2: Export the component

export default Header;

Step 3: Import and use the component

import Header from "./Header";

function App() {
  return (
    <div>
      <Header />
      <p>Welcome to my website.</p>
    </div>
  );
}

export default App;

Explanation:

  • Header is the component's name.
  • export default Header exports it as the file's default export.
  • import Header from "./Header" imports it into another module.
  • renders the component inside another component.

6. How to Use Components in React

After defining a component, you can use it in JSX as a custom element. A custom React component's name should begin with an uppercase letter.

Example

function Message() {
  return <p>This is a reusable message component.</p>;
}

function App() {
  return (
    <div>
      <h1>My Application</h1>
      <Message />
      <Message />
      <Message />
    </div>
  );
}

export default App;

Here, the same Message component is used three times. React renders the message wherever the component is included.

Important rules

  • Use uppercase names for custom React components.
  • Use lowercase names for standard HTML elements such as div, p, and button.
  • Use matching opening and closing tags, or self-closing syntax when the component has no children.
  • Define components at the top level of a module rather than defining a component inside another component.

7. Understanding Component Composition

Component composition means building a larger interface by combining smaller components. A component can render other components inside its own JSX.

Example

function Header() {
  return <header><h1>Online Store</h1></header>;
}

function Product() {
  return (
    <article>
      <h2>Wireless Headphones</h2>
      <p>Price: ₹1,999</p>
    </article>
  );
}

function Footer() {
  return <footer>Thank you for visiting!</footer>;
}

function App() {
  return (
    <>
      <Header />
      <main>
        <Product />
      </main>
      <Footer />
    </>
  );
}

export default App;

In this example, the App component combines Header, Product, and Footer to create a complete page.

Benefits of composition

  • Creates a clear UI structure.
  • Encourages reuse of smaller components.
  • Reduces repeated markup.
  • Makes the application easier to extend.

8. Understanding Props in Components

Props, short for properties, allow a parent component to pass data to a child component. Props can contain strings, numbers, booleans, arrays, objects, functions, and other React nodes.

Example

function Student(props) {
  return (
    <div>
      <h2>Name: {props.name}</h2>
      <p>Course: {props.course}</p>
    </div>
  );
}

function App() {
  return (
    <div>
      <Student name="Aarav" course="React JS" />
      <Student name="Priya" course="JavaScript" />
    </div>
  );
}

export default App;

The Student component receives different values for name and course, allowing the same component to display different information.

Using destructuring

function Student({ name, course }) {
  return (
    <div>
      <h2>Name: {name}</h2>
      <p>Course: {course}</p>
    </div>
  );
}

Destructuring extracts values from the props object and often makes component code easier to read. Props should be treated as read-only; a child should not modify the props object.


9. Understanding the Children Prop

The special children prop contains content placed between a component's opening and closing tags. It helps create reusable layout and container components.

Example

function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}

function App() {
  return (
    <Card>
      <h2>React Components</h2>
      <p>Build your UI using reusable pieces.</p>
    </Card>
  );
}

export default App;

In this example, the heading and paragraph are passed into Card as its children. The Card component decides where that content appears.


10. Components and State

State is data managed by a component that can change over time. When state changes through a React state setter, React can render the component again to reflect the updated data.

Function components commonly use the useState Hook to manage local state.

Example: Counter component

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  function handleIncrement() {
    setCount(previousCount => previousCount + 1);
  }

  return (
    <div>
      <h2>Counter: {count}</h2>
      <button type="button" onClick={handleIncrement}>
        Increase
      </button>
    </div>
  );
}

export default Counter;

How it works:

  • useState(0) initializes the counter to zero.
  • count holds the current state value.
  • setCount updates the state.
  • handleIncrement increases the counter when the button is clicked.
  • React renders the updated count in the UI.

11. Parent and Child Components

A parent component renders another component inside its JSX. The rendered component is called a child component in that relationship. A component can be a parent in one relationship and a child in another.

Example

function Child() {
  return <p>I am the child component.</p>;
}

function Parent() {
  return (
    <section>
      <h2>I am the parent component.</h2>
      <Child />
    </section>
  );
}

function App() {
  return <Parent />;
}

export default App;

In this example, Parent renders Child, and App renders Parent.

Passing data from parent to child

function Child({ message }) {
  return <p>{message}</p>;
}

function Parent() {
  return (
    <Child message="Data passed from parent to child" />
  );
}

Props are the standard way to pass information from a parent to a child. When a child needs to request a change, the parent can pass a callback function as a prop.


12. Component File Organization

In small examples, several components may appear in one file. In larger applications, it is common to organize components into separate files and folders.

Example folder structure

src/
├── components/
│   ├── Header.jsx
│   ├── Footer.jsx
│   ├── Button.jsx
│   └── ProductCard.jsx
├── pages/
│   └── Home.jsx
├── App.jsx
└── main.jsx

This is an example structure, not a mandatory React requirement. The best structure depends on the size and needs of the application.

Example: Header.jsx

function Header() {
  return (
    <header>
      <h1>My React App</h1>
    </header>
  );
}

export default Header;

Example: App.jsx

import Header from "./components/Header";

function App() {
  return (
    <div>
      <Header />
      <p>Welcome to the application.</p>
    </div>
  );
}

export default App;

13. Default Exports and Named Exports

Components can be exported from a JavaScript module using a default export or a named export.

Default export

function Header() {
  return <h1>Website Header</h1>;
}

export default Header;

Import a default export without curly braces:

import Header from "./Header";

Named export

export function Header() {
  return <h1>Website Header</h1>;
}

export function Footer() {
  return <footer>Website Footer</footer>;
}

Import named exports using curly braces:

import { Header, Footer } from "./Layout";
Feature Default export Named export
Syntax export default Header export function Header()
Import syntax import Header from "./Header" import { Header } from "./Layout"
Number per module One default export Multiple named exports
Imported name Can choose a local name Usually matches the exported name, unless aliased

14. Components and JSX

JSX is a syntax extension that allows developers to write HTML-like markup inside JavaScript. React components often use JSX to describe the UI they render.

Example

function Greeting() {
  const name = "Riya";

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>Welcome to React.</p>
    </div>
  );
}

JSX makes it convenient to keep a component's UI description near the JavaScript logic that supports it.

Important JSX rules

  • Return a single JSX expression, using a parent element or Fragment when needed.
  • Use className instead of class for CSS classes.
  • Use curly braces to embed JavaScript expressions.
  • Close tags correctly, including self-closing elements.
  • Use uppercase names for custom components.

15. Conditional Rendering in Components

Conditional rendering means displaying different UI depending on a condition, such as whether a user is logged in or whether a list contains items.

Example

function LoginMessage({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h2>Welcome back!</h2>;
  }

  return <h2>Please log in.</h2>;
}

export default LoginMessage;

The component displays a different heading based on the value of isLoggedIn.

Using a ternary expression

function Status({ isAvailable }) {
  return (
    <p>
      {isAvailable ? "Available" : "Unavailable"}
    </p>
  );
}

Use conditional rendering when the UI needs to change based on props, state, or other JavaScript conditions.


16. Rendering Multiple Components with Lists

React can render collections of components using JavaScript array methods such as map(). Each rendered sibling in a list should have a stable, unique key.

Example

const students = [
  { id: 1, name: "Aarav" },
  { id: 2, name: "Priya" },
  { id: 3, name: "Rohan" }
];

function StudentList() {
  return (
    <ul>
      {students.map(student => (
        <li key={student.id}>
          {student.name}
        </li>
      ))}
    </ul>
  );
}

export default StudentList;

The map() method creates a list item for each student. The key helps React identify each item when the list changes.


17. Component Lifecycle: Basic Introduction

A component's lifecycle describes the stages it may go through while being displayed and updated in an application.

Stage Meaning
Mount The component is added to the UI.
Update The component renders again because relevant props, state, or context have changed.
Unmount The component is removed from the UI.

In function components, Hooks such as useEffect can synchronize with external systems and provide cleanup when necessary. Class components have lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount.

Not every component needs an effect. Use effects when synchronizing with an external system, not simply to calculate values that can be derived during rendering.


18. Best Practices for Creating Components

  • Use meaningful component names in PascalCase.
  • Prefer function components for most new React code.
  • Keep components focused on a clear responsibility.
  • Reuse components when the same UI pattern appears multiple times.
  • Pass information through props instead of hardcoding repeated content.
  • Keep props read-only and avoid directly mutating state.
  • Define components at the top level rather than inside another component.
  • Use semantic HTML and accessible labels.
  • Use stable keys when rendering lists.
  • Keep JSX readable and move complex logic into suitable helper functions.
  • Separate components into files when it improves organization.
  • Test important component behavior and user interactions.

19. Common Mistakes When Working with Components

Mistake Correct approach
Using a lowercase name for a custom component Use an uppercase name such as ProfileCard.
Defining a component inside another component Define components at the top level of the module.
Forgetting to import a component Import it from the correct file before using it.
Using the wrong export/import syntax Match default exports with default imports and named exports with named imports.
Trying to modify props Pass new values from the parent or use state for changing data.
Rendering list items without keys Provide stable keys unique among siblings.
Putting too much logic in one component Split responsibilities into smaller components and helper functions.
Using an extra wrapper without a purpose Use a meaningful semantic element or a Fragment where appropriate.

20. Practical Project: Simple Student Dashboard

This example combines several components to create a small student dashboard.

function Header() {
  return (
    <header>
      <h1>Student Dashboard</h1>
    </header>
  );
}

function StudentInfo({ name, course }) {
  return (
    <section>
      <h2>Student Information</h2>
      <p>Name: {name}</p>
      <p>Course: {course}</p>
    </section>
  );
}

function CourseList() {
  const courses = [
    { id: 1, name: "React JS" },
    { id: 2, name: "JavaScript" },
    { id: 3, name: "HTML and CSS" }
  ];

  return (
    <section>
      <h2>Enrolled Courses</h2>
      <ul>
        {courses.map(course => (
          <li key={course.id}>{course.name}</li>
        ))}
      </ul>
    </section>
  );
}

function Footer() {
  return (
    <footer>
      <p>Keep learning every day!</p>
    </footer>
  );
}

function App() {
  return (
    <div>
      <Header />
      <main>
        <StudentInfo name="Aarav" course="React JS" />
        <CourseList />
      </main>
      <Footer />
    </div>
  );
}

export default App;

Concepts covered

  • Creating function components.
  • Composing a page from smaller components.
  • Passing data through props.
  • Rendering lists with map().
  • Using stable keys.
  • Organizing content with semantic HTML.

21. Interview Questions and Answers

Q1. What is a component in React?

Answer: A component is a reusable piece of a React user interface that describes how a part of the application should appear and behave.

Q2. What are the main types of React components?

Answer: The two common types are function components and class components. Function components are recommended for most new React development.

Q3. Why are components useful?

Answer: Components improve reusability, readability, maintainability, testing, and application organization.

Q4. What are props?

Answer: Props are inputs passed to a component, usually by its parent, to customize its output or behavior.

Q5. What is component composition?

Answer: Component composition means combining smaller components to create a larger interface.

Q6. What is the difference between props and state?

Answer: Props are inputs received by a component. State is data managed by React state mechanisms that can change over time and trigger a re-render.

Q7. What is the purpose of the children prop?

Answer: It provides the content nested between a component's opening and closing tags, enabling flexible wrapper and layout components.

Q8. Can one component be used multiple times?

Answer: Yes. A component can be rendered multiple times, and each instance can receive different props.

Q9. Why should custom component names start with uppercase letters?

Answer: JSX uses uppercase names to identify custom React components and lowercase names for built-in HTML elements.

Q10. What is the difference between default and named exports?

Answer: A module can have one default export and multiple named exports. Their corresponding import syntax is different.

Q11. What is a key in React?

Answer: A key is a special value used to help React identify list items between renders.

Q12. What does useState do?

Answer: It is a React Hook that lets a function component add and update state.


22. Revision Checklist

  • Understand what a React component is.
  • Know why components are important.
  • Distinguish function components from class components.
  • Create, export, import, and render components.
  • Understand component composition and nesting.
  • Pass data through props.
  • Use the children prop for nested content.
  • Understand state and the useState Hook.
  • Use conditional rendering.
  • Render lists with stable keys.
  • Organize components into suitable files.
  • Follow component naming and accessibility best practices.

23. Conclusion

Components are one of the most important concepts in React JS. They allow developers to divide a user interface into reusable, independent pieces and combine those pieces to build complete applications. By understanding function components, props, state, composition, and component organization, you can create React applications that are easier to develop, test, and maintain.

Continue learning with the JustAcademy React JS Training Course or register for a React JS course demo.

Official React Documentation

whatsapp